$('#xsdglForm').tabs({
    border: false,
    onSelect: function (title) {
        if (title == "销售单打印") {
            if (null == $("[name='xsd.id']").val() || $("[name='xsd.id']").val() == '') {
                $.messager.alert('提示', '先保存销售信息，才能打印销售单！', 'info');
                $('#xsdglForm').tabs('select', "销售信息");
            } else {
                $.ajax({
                    type: "POST",
                    url: $.webPath() + '/xsgl/xsdgl/xsdDetail?xsdId=' + $("input[name='xsd.id']").val(),
                    dataType: "html",
                    beforeSend: function () {
                        $.messager.progress();
                    },
                    success: function (data) {
                        $.messager.progress("close");
                        $('#xsddy_xsd_id').html(data);
                        //=====================保供销售显示库存单价和库存金额    [name='bgxs_name']
                        var xslx = $("#xsd_content_xslx").val();
                        if (xslx == "bgxs") {
                            $("[name='bgxs_name']").show();
                        } else {
                            $("[name='bgxs_name']").hide();
                        }
                    }
                });
            }
        }
    }
});
//=============按钮事件=============================
//  点击出售联，隐藏出库重量
function cslClick(tdName) {
    $("[name='" + tdName + "']").show();
    $("#xsddy_ck").hide();
    // $("#xsddy_tdrq").hide();

    $("#xsd_csl").show();
    $("#xsd_thd").hide();
    $("#xsd_shd").hide();
}
/*//点击 记账联，显示出库重量
 function jzlClick(tdName) {
 //alert(tdName);
 $("[name='" + tdName + "']").show();
 }*/
//点击 提货单，显示出库重量
function thdClick(tdName) {
    $("[name='" + tdName + "']").hide();
    $("#xsddy_ck").hide();
    //  $("#xsddy_tdrq").hide();

    $("#xsd_csl").hide();
    $("#xsd_thd").show();
    $("#xsd_shd").hide();
}
//点击   送货单，显示出库重量
function shdClick(tdName) {
    $("[name='" + tdName + "']").hide();
    $("#xsddy_ck").show();
    // $("#xsddy_tdrq").show();

    $("#xsd_csl").hide();
    $("#xsd_thd").hide();
    $("#xsd_shd").show();
}

//============按钮事件========================================


// 销售配送单打印预览
function xsddyPrintPreview() {
    var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('XSDCONTENT_LODOP_EM'));
    LODOP.SET_PRINT_STYLEA(0, "NotOnlyHighPrecision", true);
    LODOP.PRINT_INIT("预览销售单");
//    var inputs = document.getElementById("page").getElementsByTagName("input");
//    for (var i = 0; i < inputs.length; i++) {
//        inputs[i].setAttribute("value", inputs[i].value);
//    }
    var strBodyStyle = "<style  type=\"text/css\">" +
        ".textcon{padding:8px;}" +
        ".input-tian{border-top:0 none;border-left:0 none;border-right:0 none;border-bottom: 1px solid black;height:22px;line-height:22px;width:100%;font-weight: bold;}" +
        " select{display:none}" +
        ".tb{width:auto;border-collapse:collapse;border-spacing:0;}" +
        ".tb th{padding:2px 2px 2px 12px;font-size:12px;font-weight:normal;text-align: right;}" +
        ".tb td{padding:2px;font-size:12px;}" +
        ".tb caption{ font-size:24px;height:60px;line-height:20px;}" +
        ".intb{width: 100%;}" +
        ".intb,.intb th,.intb td{border:1px solid black;}" +
        "</style>";
    var strFormHtmltop = strBodyStyle + "<div class='textcon'>" + document.getElementById("xsddy_print_id").innerHTML + "</div>";
    var strFormHtmlbody = strBodyStyle + "<div class='textcon'>" + document.getElementById("xsddy_xsd_id").innerHTML + "</div>";
    var strFormHtmlBottom = strBodyStyle + "<div class='textcon'>" + document.getElementById("xsddy_xia_id").innerHTML + "</div>";
    var xsd_xsdh = $("#xsd_xsdh").val();
    var xsd_ewmtime = $("#xsd_ewmtime").val();


//    LODOP.SET_PRINT_PAGESIZE(0, '2640', '2790', "CreateCustomPage");
//    LODOP.ADD_PRINT_HTM(50, 80, "82%", "90%", strFormHtmltop + strFormHtmlbody + strFormHtmlBottom);
//    LODOP.ADD_PRINT_BARCODE(50, "85%", 90, 90, 'QRCode', xsd_xsdh + " " + xsd_ewmtime);
    LODOP.ADD_PRINT_TABLE(135, "1.5%", "90%", 350, strFormHtmlbody);
    LODOP.SET_PRINT_STYLEA(0, "Vorient", 3);
    LODOP.ADD_PRINT_HTM(20, "1.5%", "90%", 145, strFormHtmltop);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 1);
    LODOP.SET_PRINT_STYLEA(0, "LinkedItem", 1);
    LODOP.ADD_PRINT_HTM(495, "1.5%", "90%", 200, strFormHtmlBottom);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 1);
    LODOP.SET_PRINT_STYLEA(0, "LinkedItem", 1);
//    LODOP.ADD_PRINT_BARCODE(20, "85%", 90, 90, 'QRCode', xsd_xsdh + " " + xsd_ewmtime);
//    LODOP.SET_PRINT_STYLEA(0, "QRCodeVersion", 3);
    LODOP.ADD_PRINT_TEXT(5, "80%", 135, 20, "总页号：第#页/共&页");
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 2);
    LODOP.SET_PRINT_STYLEA(0, "Horient", 1);
    LODOP.PREVIEW();
}

//销售单打印
function xsddyPrint() {
    var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('XSDCONTENT_LODOP_EM'));
    LODOP.SET_PRINT_STYLEA(0, "NotOnlyHighPrecision", true);
    LODOP.PRINT_INIT("打印销售单");
    LODOP.SET_PRINT_STYLE("FontSize", 18);

    var inputs = document.getElementById("xsddy_id").getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].setAttribute("value", inputs[i].value);
    }
    var strBodyStyle = "<style type=\"text/css\">" +
        ".textcon{padding:8px;}" +
        ".input-tian{border-top:0 none;border-left:0 none;border-right:0 none;border-bottom: 1px solid black;height:22px;line-height:22px;width:100%;font-weight: bold;}" +
        " select{display:none}" +
        ".tb{width:auto;border-collapse:collapse;border-spacing:0;}" +
        ".tb th{padding:2px 2px 2px 12px;font-size:12px;font-weight:normal;text-align: right;}" +
        ".tb td{padding:2px;font-size:12px;}" +
        ".tb caption{ font-size:24px;height:60px;line-height:20px;}" +
        ".intb{width: 100%;}" +
        ".intb,.intb th,.intb td{border:1px solid black;}" +
        "</style>";
    var strFormHtmltop = strBodyStyle + "<div class='textcon'>" + document.getElementById("xsddy_print_id").innerHTML + "</div>";
    var strFormHtmlbody = strBodyStyle + "<div class='textcon'>" + document.getElementById("xsddy_xsd_id").innerHTML + "</div>";
    var strFormHtmlBottom = strBodyStyle + "<div class='textcon'>" + document.getElementById("xsddy_xia_id").innerHTML + "</div>";
    var xsd_xsdh = $("#xsd_xsdh").val();
    var xsd_ewmtime = $("#xsd_ewmtime").val();


//    LODOP.SET_PRINT_PAGESIZE(0, '2640', '2790', "CreateCustomPage");
//    LODOP.ADD_PRINT_HTM(50, 80, "82%", "90%", strFormHtmltop + strFormHtmlbody + strFormHtmlBottom);
//    LODOP.ADD_PRINT_BARCODE(50, "85%", 90, 90, 'QRCode', xsd_xsdh + " " + xsd_ewmtime);
    LODOP.ADD_PRINT_TABLE(135, "1.5%", "90%", 350, strFormHtmlbody);
    LODOP.SET_PRINT_STYLEA(0, "Vorient", 3);
    LODOP.ADD_PRINT_HTM(20, "1.5%", "90%", 145, strFormHtmltop);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 1);
    LODOP.SET_PRINT_STYLEA(0, "LinkedItem", 1);
    LODOP.ADD_PRINT_HTM(495, "1.5%", "90%", 200, strFormHtmlBottom);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 1);
    LODOP.SET_PRINT_STYLEA(0, "LinkedItem", 1);
    LODOP.ADD_PRINT_TEXT(5, "80%", 135, 20, "总页号：第#页/共&页");
    LODOP.SET_PRINT_STYLEA(0, "ItemType", 2);
    LODOP.SET_PRINT_STYLEA(0, "Horient", 1);
    LODOP.PREVIEW();
}


$(function () {
    $("a.ljtip").ljDetail($("#xsd_xsht_id").val());
    //加载客户
//    $("#xsd_kh_id").qyjgcomboboxforsearch({
//        onLoadSuccess:function () {
//            if ($("#kh_id").val()) {
//                $(this).combobox('setValue', $("#kh_id").val());
//                $(this).combobox('setText', $("#kh_jc").val());
//                $("#xsd_gc_id").gccombobox($("#kh_id").val());
//            }
//        },
//        onSelect:function () {
//            var xsd_kh = $("#xsd_kh_id").combobox('getValue');
//            $("#xsd_gc_id").gccombobox(xsd_kh);
//        }
//    });

    $("#xsd_kh_id").qyjgzcombobox({
        onSuccess: function () {
            $("#xsd_kh_id").zcombobox("setMap", { id: $("#kh_id").val(), jc: $("#kh_jc").val()});
          /*  $("#xsd_gc_id").gccombobox($("#kh_id").val());*/
        },
        onSelect: function () {
            var xsd_kh = $("#xsd_kh_id").combobox('getValue');
         /*   $("#xsd_gc_id").gccombobox(xsd_kh);*/
        }
    });

    //协办公司加载
    $("[name='xsd.xbgs.id']").jgbmtree($("[name='xsd.xbbm.id']"), undefined,
        $("#xsd_xbbm").val(), undefined)
    //发运责任
    $("[name='xsd.fyzr.id']").sjzdcombobox('fyzr', {
        onLoadSuccess: function () {
            if (!$("#xsd_fyzr_id").combobox('getValue'))
                $("[name='xsd.fyzr.id']").val(42)
        }
    });
    //工程
//    $("[name='xsd.gc.id']").combobox({'textField':'mc','idField':'id'});
    //仓库
/*    $("[name='xsd.thck.id']").combobox({
        url: $.webPath() + '/organ/ck/ckmcXsdList?ssgsjgId=' + $("#xsd_xsgs_id").val(),
        valueField: 'id',
        textField: 'mc',
        multiple: false,
        panelHeight: '200',
        filter: function (q, row) {
            var opts = $(this).combobox('options');
            return row[opts.textField].indexOf(q) >= 0;
        }
    })*///.ckcombobox($("#xsd_xsgs_id").val());

    $("#xsd_thck_id").combobox({
        url:$.webPath() + '/organ/ck/ywsfckmcList',
        valueField:'id',
        textField:'mc',
        panelHeight:'200',
        editable:true
    });

    /*$("#xsd_xsgs_id").combobox({
        onSelect: function (record) {
            $("#xsd_thck_id").combobox('reload', $.webPath() + '/organ/ck/ckmcXsdList?ssgsjgId=' + record.value);
        }
    })*/

    initXsdContent();


    $("#xsd_xsht_id").combogrid({
//        panelWidth: 630,
        delay: 500,
        mode: 'remote',
        idField: 'id',
        textField: 'htbm',
        fitColumns: true,
        pagination: true, //是否分页
        rownumbers: true, //序号
        collapsible: false, //是否可折叠的
        fit: true, //自动大小
        pageSize: 10, //每页显示的记录条数，默认为10
        url: $.webPath() + '/htgl/xshtgl/xshtSimpleList?zt=ysp',
        columns: [
            [
                {field: 'htbm', title: '合同编码', width: 100},
                {field: 'xhtbm', title: '来源系统合同号', width: 80},
                {field: 'hzf_qc', title: '客户', width: 80},
                {field: 'qdrq', title: '签订日期', width: 80},
                {field: 'sbr_xm', title: '申报人', width: 80},
                {field: 'jsrq', title: '结束日期', width: 80}
            ]
        ],
        onChange: function (newValue, oldValue) {
            var g = $(this).combogrid('grid');
            var row = g.datagrid('getSelected');
            if (row) {
                initXsd(row);
                var href = $.webPath() + '/htgl/xshtgl/xshtgl_xsmx?xshtId=' + row.id;
                $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
                    xsdmxGrid(href, data);
                })
            }
        },
        onSelect: function (rowIndex, rowData) {
            if (rowData) {
                $("#xsd_ll").val(rowData['lj_ll']);
                if (rowData['htxz.z'] == "标准合同") {
                    $("#xsdgl_xsdmx_toolbar").css('display', 'none');
                } else {
                    $("#xsdgl_xsdmx_toolbar").css('display', 'block');
                }
            }
        }
    });

    $("#exportBindNo").click(function () {
        var win = $.window({
            title: "批量导入",
            width: 450,
            height: 240,
            cache: false,
            url: $.webPath() + "/xsgl/xsdgl/xsdmx_upload",
            modal: true,
            buttons: [
                {
                    text: '确认',
                    handler: function () {
                        $('#xsdmx_uploadSubject').form('submit', {
                            onSubmit: function () {
                                $(win).mask();
                            },
                            success: function (bingNos) {
                                $(win).mask('hide');
                                $(win).window('close');
                                var href = $.webPath() + '/htgl/xshtgl/xshtgl_xsmx_kbh?bindNos=' + bingNos;
                                $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
                                    xsdmxGrid(href, data);
                                })
                            }
                        });
                    }
                }
            ]
        });
    })

    //筛选物资明细
    $("#filterMaterial").click(function () {
        var xsd_xsht_id = $("#xsd_xsht_id").combobox("getValue");
        if (xsd_xsht_id) {
            searchXshtCorKhWindow(shaixuanwuzimingxifankuihanshuo, 1, xsd_xsht_id);
        } else {
            $.messager.alert("提示", "请先选择销售合同!", "info");
        }

    })

    //计算价格
    $("#xsdgl_xsdmx_toolbar [name='countprice']").click(function () {
        $('#xsd_mx').datagrid('acceptChanges');
        var rows = $("#xsd_mx").datagrid('getChecked');
        if (rows.length == 0) {
            $.messager.alert("提示", "请勾选要计算价格的物资!", "info");
        } else {
            var flag = true;
            $.each(rows, function (i, val) {
                if (val['kh.id'] == null) {
                    $.messager.alert("提示", "第" + (i + 1) + "行没有选择卡号", "info");
                    flag = false;
                }
            });
            if (flag == true) {
                var khIds = [];
                $.each(rows, function (i, val) {
                    khIds.push(val['kh.id']);
                });
                $.post($.webPath() + '/xsgl/xsdgl/computerprice', {'khIds': khIds.join(",")}, function (data) {
                    var obj = eval('(' + data + ')');
                    kh_searchWindowCountPrice(obj);
                })
            }
        }
    });


   /* //新增合同费用
    $("#xsdgl_xsdfy_toolbar [name='xzxsdfy']").click(function () {
        var jfsl = countSumXsdmxforfylbChange('sbsl');
        var data = {
            'sydw.id': null,
            'fylb.id': null,
            'jfsl': jfsl,
            'dj': 0,
            'je': 0,
            'bz': null
        };
        $("#xsd_fy").edatagrid('appendRow', data);
    });
    //删除合同费用
    $("#xsdgl_xsdfy_toolbar [name='scxsdfy']").click(function () {
        var rows = $("#xsd_fy").edatagrid('getChecked');
        if (rows) {
            $.messager.confirm('提示', '是否确定删除销售费用?', function (r) {
                if (r) {
                    $.each(rows, function (i, val) {
                        var index = $("#xsd_fy").edatagrid('getRowIndex', val);
                        $("#xsd_fy").edatagrid('deleteRow', index);
                    });
                }
            });
        }
        $("#xsd_fy").edatagrid('resize');
    });*/


    $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
        var xsdId = !$("[name='xsd.id']").val() ? 0 : $("[name='xsd.id']").val();
        xsdmxGrid($.webPath() + '/xsgl/xsdgl/xsdgl_xsmx?xsdId=' + xsdId, data);
    })

  /*  $.post($.webPath() + '/organ/wls/wlsInuseList', function (jgdata) {
        $.post($.webPath() + '/cwgl/kmys/cyfyys/fylbcombobox', {'gsId': $("#xsd_xsgs_id").val()}, function (data) {
            var xsdId = !$("[name='xsd.id']").val() ? 0 : $("[name='xsd.id']").val();
            xsdfyGrid($.webPath() + '/xsgl/xsdgl/xsdgl_xsfy?xsdId=' + xsdId, jgdata, data);
        })
    })*/


   /* $("#btn_xsd_addlskh").click(function () {
        xsdAddLskh('新增库存零售客户', 'add_lskh');
    });*/
})

/*function xsdAddLskh(title, action) {
    var href = $.webPath() + "/xsgl/xsdgl/kclskh_content";
    var actionUrl = $.webPath() + "/organ/qyjg/add_lskh";
    kclskh_showDialog(title, href, actionUrl);
};

//弹框调用方法
function kclskh_showDialog(title, href, actionUrl) {
    var buttons = [
        {
            id: 'kclskh_save',
            text: '保存',
            handler: function () {
                $(win).mask();
                $('#lskhForm').form('submit', {
                    url: actionUrl,
                    success: function (data) {
                        $(win).mask('hide');
                        var json = $.parseJSON(data);
                        if (json.statusCode == 200) {
                            $(win).window('close');
                            $("#xsd_kh_id").zcombobox("setMap", { id: json.id, jc: json.jc});
                        } else
                            $.messager.alert('提示', json.message, 'error');
                    }
                });
            }
        }
    ]
    var win = $.window({
        title: title,
        iconCls: 'icon-add2',
        width: 600,
        height: 155,
        cache: false,
        url: href,
        modal: true,
        buttons: buttons
    });
}*/
function xsdmxGrid(href, fsOptions) {
    $("#xsd_mx").edatagrid({
        url: href,
        fitColumns: false,
        singleSelect: true,
        fit: true,
//        width: 1350,
//        height:385,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        rownumbers: true,
        showFooter: true,
        toolbar: "#xsdgl_xsdmx_toolbar",
        frozenColumns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'wzgg.id', title: '物资编码ID', hidden: true},
                {field: 'wzgg.code', title: '物资编码', hidden: true},
                {field: 'xszxh', title: '合同子项号', width: 85},
                {field: 'wzgg.name', title: '品名', width: 100},
                {field: 'wzgg.cz', title: '材质', width: 85},
                {field: 'wzgg.ggxh', title: '规格', width: 85},
                {field: 'carNo', title: '车皮号', width: 85},
                {field: 'bindNo', title: '捆包号', width: 85},
                {field: 'wzgg.th', title: '图号', hidden: true},
                {field: 'ck', title: '长宽', editor: {type: 'text'}, hidden: true},
//                {field: 'wzgg.dw', title: '单位', width: 30},

                {field: 'jzfs.id', formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].z;
                    }
                    return value;
                }, title: '记重方式', width: 50}
            ]
        ],
        columns: [
            [
               /* {field: 'kh.khbm', title: '卡号', width: 130},*/
                {field: 'xscb', title: '库存单价',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 70},
                {field: 'js', title: '件数',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 70},
                {field: 'sbsl', title: '数量（吨）',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 100},
                {field: 'hsj', title: '合同单价(含税)',
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }, width: 100},
                {field: 'bhsj', title: '合同单价(不含税)',
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }, width: 100},
                {field: 'hse', title: '含税额(元)',
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }, width: 100},
                {field: 'bhse', title: '无税额(元)',
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }, width: 100}
            ]
        ],
        loadFilter: function (data) {
            $.each(data.rows, function () {
                var bhsj = Math.round(this.bhsj * 10000) / 10000;
                var hsj = Math.round(this.hsj * 10000) / 10000;
                var sl = Math.round(this.sbsl * 10000) / 10000;

                if (this.bhsj) {
                    this.bhse = Math.round(multiply(sl, bhsj) * 100) / 100;
                }
                if (this.hsj) {
                    this.hse = Math.round(multiply(sl, hsj) * 100) / 100;
                }
            })
            return data;
        },
        onSelect: function (rowIndex, rowData) {
//            //获取每个单元格
//            $("#xsd_mx").edatagrid('editRow', rowIndex);
//            var editors = $("#xsd_mx").datagrid('getEditors', rowIndex);
//            if (editors.length == 0)
//                return;
//            var khEditor = editors[2];//申报重量编辑框
//            var jsEditor = editors[3];
//            var sbslEditor = editors[4];
//            var hsjEditor = editors[5];
//            var hseEditor = editors[7];
//            var bhsjEditor = editors[6];
//            var bhseEditor = editors[8];
//
//            jsEditor.target.unbind("change").bind('change', function () {
//                $(jsEditor.target).numberbox('setValue', $(jsEditor.target).val());
//                var cdVal = rowData['cd.id'];
//                if (cdVal != "" && cdVal) {
//                    var selected = $('#xsd_mx').datagrid('getSelected');
//                    $.post($.webPath() + '/cggl/cgdgl/get_jz', {'ggId': selected['wzgg.id'], cdId: cdVal}, function (data) {
//                        var obj = eval('(' + data + ')');
//                        if (obj.jz && obj.jz != '') {
//                            $(sbslEditor.target).numberbox('setValue', parseFloat(obj.jz) * $(jsEditor.target).numberbox('getValue'));
//                        } else {
//                            $(sbslEditor.target).numberbox('setValue', 0);
//                            $.messager.alert('提示', '此物资未存单位件重，请手动填写申报数量', 'info');
//                        }
//                    })
//                }
//            });
//
//            sbslEditor.target.unbind("change").bind('change', function () {
//                $(sbslEditor.target).numberbox('setValue', $(sbslEditor.target).val());
////                $(hsjEditor.target).numberbox('setValue', 0);
////                $(bhsjEditor.target).numberbox('setValue', 0);
////                $(bhseEditor.target).numberbox('setValue', 0);
////                $(hseEditor.target).numberbox('setValue', 0);
//                changeEidtToSum(rowIndex, jsEditor, sbslEditor, hseEditor, bhseEditor, hsjEditor, bhsjEditor);
//            });
//
//            hsjEditor.target.unbind("change").bind('change', function () {
//                $(hsjEditor.target).numberbox('setValue', $(hsjEditor.target).val());
//                var bhsj = tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#xsd_sl").combobox('getValue'));
//                if (!$(bhsjEditor.target).numberbox('getValue'))
//                    $(bhsjEditor.target).numberbox('setValue', bhsj);
//                else if (Math.abs($(bhsjEditor.target).numberbox('getValue') - bhsj) >= 0.01) {
//                    $(bhsjEditor.target).numberbox('setValue', bhsj);
//                }
//                changeEidtToSum(rowIndex, jsEditor, sbslEditor, hseEditor, bhseEditor, hsjEditor, bhsjEditor);
//            });
//            bhsjEditor.target.unbind("change").bind('change', function () {
//                $(bhsjEditor.target).numberbox('setValue', $(bhsjEditor.target).val());
//                var hsj = tax.getIncludingTaxPrice($(bhsjEditor.target).numberbox('getValue'), $("#xsd_sl").combobox('getValue'));
//                if (!$(hsjEditor.target).numberbox('getValue'))
//                    $(hsjEditor.target).numberbox('setValue', hsj);
//                else if (Math.abs($(hsjEditor.target).numberbox('getValue') - hsj) > 0.01) {
//                    $(hsjEditor.target).numberbox('setValue', hsj);
//                }
//                changeEidtToSum(rowIndex, jsEditor, sbslEditor, hseEditor, bhseEditor, hsjEditor, bhsjEditor);
//            });
//
//
//            //绑定事件
//            //弹出卡号树
//            khEditor.target.unbind("dblclick").bind('dblclick', function () {
//                var thck_id = $("#xsd_thck_id").combobox('getValue');
//                var xsgs_id = $("#xsd_xsgs_id").combobox('getValue');
////                var kh_id=$("#")
//                var sbgs_id = $("#xsd_kh_id").val();
//                if (thck_id)
//                    searchkhwindow(kh_searchWindowOKbtnHandler, thck_id, xsgs_id, sbgs_id, rowData['cd.id'], rowData['wzgg.id']);
//                else {
//                    $('#xsdglForm').tabs('select', "销售信息");
//                    $.messager.alert("提示", "请选择提货仓库!", "info");
//                }
//            });
        },
        onLoadSuccess: function () {
            countSumXsd();
        }
    })
}


$("#xsdgl_xsdmx_toolbar [name='scxsdmx']").click(function () {
    var rows = $("#xsd_mx").edatagrid('getChecked');
    if (rows) {
        $.messager.confirm('提示', '是否确定删除销售单明细?', function (r) {
            if (r) {
                $.each(rows, function (i, val) {
                    var index = $("#xsd_mx").edatagrid('getRowIndex', val);
                    $("#xsd_mx").edatagrid('deleteRow', index);
                });
                //countSumXsdmx();
            }
        });
    }
    $("#xsd_mx").edatagrid('resize');
});

//查询物资代码确定按钮回调函数
//function xsdmx_searchWindowOKbtnHandler(data) {
//    var rowdatas = $.map(data, function (n, i) {
//        var wsdj = Math.round(n.wsdj * 10000) / 10000;
//        var ll = Math.round((1 + $("#xsd_ll").val() / 100) * 10000) / 10000;
//        var shuil = Math.round((1 + $("#xsd_sl").combobox('getValue') / 100) * 10000) / 10000;
//        var sl = Math.round(n.sl * 1000) / 1000;
//
//        var hsj = Math.round(multiply(multiply(wsdj, ll), shuil) * 10000) / 10000;
//        var bhsj = Math.round(multiply(wsdj, ll) * 10000) / 10000;
//
//        return {
//            'kh.id': n.id,
//            'kh.khbm': n.khbm,
//            'wzgg.id': n.jtwz_id,
//            'wzgg.oldcode': n.jtwz_oldcode,
//            'wzgg.code': n.jtwz_code,
//            'wzgg.name': n.jtwz_name,
//            'wzgg.ggxh': n.jtwz_ggxh,
//            'wzgg.th': n.jtwz_th,
//            'wzgg.dw': n.jtwz_dw,
//            'cd.id': n.cd_id,
//            'cd.z': n.cd_z,
//            'kkdsl': Math.round(n.kkdsl * 1000) / 1000,
//            'sbsl': sl,
//            'xscb': wsdj,
//            'hsj': hsj,
//            'bhse': formatMoney(multiply(bhsj, sl)),
//            'hse': formatMoney(multiply(hsj, sl)),
//            'bhsj': bhsj,
//            'ck': '',
//            'jzfs.id': null
//        };
//    });
//    $.each(rowdatas, function () {
//        $("#xsd_mx").edatagrid('appendRow', this);
//    });
//    countSumXsd();
//}
/*
function kh_searchWindowOKbtnHandler(data) {
    var row = $("#xsd_mx").edatagrid('getSelected');
    var rowdatas = $.map(data, function (n, i) {
        var bhsj = Math.round(row['bhsj'] * 10000) / 10000;
        var hsj = Math.round(row['hsj'] * 10000) / 10000;
        var kkdsl = Math.round(n.kkdsl * 10000) / 10000;

        var sl = row['sbsl'];
        var js = row['js'];
        if (row['sbsl'] > kkdsl) {
            sl = kkdsl;
        }
        return {
            'kh.id': n.id,
            'kh.khbm': n.khbm,
            'wzgg.id': row['wzgg.id'],
            'wzgg.oldcode': row['wzgg.oldcode'],
            'wzgg.code': row['wzgg.code'],
            'wzgg.name': row['wzgg.name'],
            'wzgg.ggxh': row['wzgg.ggxh'],
            'wzgg.th': row['wzgg.th'],
            'wzgg.dw': row['wzgg.dw'],
            'cd.id': row['cd.id'],
            'cd.z': row['cd.z'],
            'kkdsl': Math.round(n.kkdsl * 10000) / 10000,
            'js': js,
            'sbsl': sl,
            'ck': '',
//            'xscb': Math.round(n.wsdj * 10000) / 10000,
            'jzfs.id': row['jzfs.id'],
            'hsj': hsj,
            'bhse': row['bhse'],
            'hse': row['hse'],
            'bhsj': bhsj
        };
    });

    var index = $("#xsd_mx").edatagrid('getRowIndex', row);
    $("#xsd_mx").edatagrid('deleteRow', index);

    $.each(rowdatas, function () {
        $("#xsd_mx").edatagrid('appendRow', this);
    });
    countSumXsd();
}*/

function kh_searchWindowCountPrice(data) {
    var flag = false;
    var row = $("#xsd_mx").edatagrid('getChecked');
    $.each(row, function (i, val) {
//        alert(data[i].shj + ":" + data[i].lxjt);
        if (!data[i].hsj) {
            data[i].hsj = 0;
            flag = true;
        }
        var index = $("#xsd_mx").edatagrid('getRowIndex', val);
        $("#xsd_mx").edatagrid('updateRow', {
            index: index,
            row: {
                'kh.id': val['kh.id'],
                'kh.khbm': val['kh.khbm'],
                'wzgg.id': val['wzgg.id'],
                'wzgg.oldcode': val['wzgg.oldcode'],
                'wzgg.code': val['wzgg.code'],
                'wzgg.name': val['wzgg.name'],
                'wzgg.ggxh': val['wzgg.ggxh'],
                'wzgg.th': val['wzgg.th'],
                'wzgg.dw': val['wzgg.dw'],
                'cd.id': val['cd.id'],
                'cd.z': val['cd.z'],
                'kkdsl': val['kkdsl'],
                'sbsl': val['sbsl'],
                'js': val['js'],
                'ck': '',
                'xscb': val['xscb'],
                'jzfs.id': val['jzfs.id'],
                'hsj': data[i].hsj,
                'bhse': Math.round(data[i].hsj * val['sbsl'] * 10000 / 1.17) / 10000,
                'hse': Math.round(data[i].hsj * val['sbsl'] * 10000) / 10000,
                'bhsj': Math.round(data[i].hsj * 10000 / 1.17) / 10000
            }
        });
        $("#xsd_mx").parent().find("tr[datagrid-row-index='" + index + "']").find("td[field='hsj']").tooltip({
            position: 'bottom',
            content: '<span style="color:#ff0000">' + data[i].jsfs + '</span>'
        });
    });
    countSumXsd();
    if (flag) {
        $.messager.alert("提示", "部分明细因缺少必要参数，系统无法计算赎货价，请自行计算！", "info");
    }
}

/*function xsdfyGrid(href, jgOptions, fsOptions) {
    $("#xsd_fy").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        rownumbers: true,
        toolbar: "#xsdgl_xsdfy_toolbar",
        columns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'sydw.id', editor: {type: 'combobox', options: {
                    data: jgOptions,
                    valueField: 'id',
                    textField: 'qc',
                    multiple: false,
                    panelHeight: '200'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < jgOptions.length; i++) {
                        if (jgOptions[i].id == value) return jgOptions[i].qc;
                    }
                    return value;
                }, title: '收益单位', width: 50},

                {field: 'fylb.id', editor: {type: 'combobox', options: {
                    data: fsOptions,
                    valueField: 'id',
                    textField: 'fykmjc',
                    multiple: false,
                    panelHeight: '110',
                    onSelect: function () {
                        var selected = $('#xsd_fy').datagrid('getSelected');
                        var rowIndex = $('#xsd_fy').datagrid('getRowIndex', selected);
                        $("#xsd_fy").edatagrid('editRow', rowIndex);
                        var editors = $("#xsd_fy").datagrid('getEditors', rowIndex);
                        if (editors.length == 0)
                            return;
                        var fylbEditor = editors[1];
                        var jfslEditor = editors[2];
                        var djEditor = editors[3];
                        var jeEditor = editors[4];
                        if ($(fylbEditor.target).combobox('getText') == "运输费") {

                            //$(jfslEditor.target).numberbox('setValue', jfsl);
                            var dj = countSumXsdmxforfylbChange('hsj');
                            $(djEditor.target).numberbox('setValue', parseFloat(dj) * 0.4);
                            var je = parseFloat($(jfslEditor.target).numberbox('getValue')) * (parseFloat(dj) * 0.4);
                            $(jeEditor.target).numberbox('setValue', je);
                        } else {
                            $(jeEditor.target).numberbox('setValue', 0);
                            $(djEditor.target).numberbox('setValue', 0);
                            //$(jfslEditor.target).numberbox('setValue', 0);
                        }
                    }
                }
                }, formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].fykmjc;
                    }
                    return value;
                }, title: '费用类别', width: 30},
                {field: 'jfsl', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '计费重量',
                    formatter: function (value) {
                        var sl = formatSl(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'dj', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '单价(元)',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'je', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 2}}, title: '金额(元)',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'bz', editor: {type: 'text'}, title: '备注', width: 50}
            ]
        ],
        onSelect: function (rowIndex) {
            //获取每个单元格
            $("#xsd_fy").edatagrid('editRow', rowIndex);
            var editors = $("#xsd_fy").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var jfslEditor = editors[2];
            var djEditor = editors[3];
            var jeEditor = editors[4];
            jfslEditor.target.unbind("blur").bind('blur', function () {
                $(jfslEditor.target).numberbox('setValue', $(jfslEditor.target).val());
                $(jeEditor.target).numberbox('setValue', $(jfslEditor.target).numberbox('getValue') * $(djEditor.target).numberbox('getValue'));
            });
            djEditor.target.unbind("blur").bind('blur', function () {
                $(djEditor.target).numberbox('setValue', $(djEditor.target).val());
                $(jeEditor.target).numberbox('setValue', $(jfslEditor.target).numberbox('getValue') * $(djEditor.target).numberbox('getValue'));
            });

        }
    })
}*/

function initXsd(r) {

  /*  if (r.xsfy_z) {
        $("#xsd_xsfy").val(r.xsfy_z);
    }*/

    if (r.lj_id) {
        var li = {id: r.lj_id, mc: r.lj_mc}
        $("#xsd_lj_id").combobox('loadData', [li]);
        $("#xsd_lj_id").combobox('setValue', r.lj_id);
        $.post($.webPath() + '/organ/ljwh/ljinfosxy', {'ljId': r.lj_id}, function (data) {
            var xydata = [];
            $(data).each(function (i, item) {
                if (item.lx == 'xy') {    //下游
                    xydata.push(item);
                }
            });
//            $("#xsd_kh_id").loadLocalRegion(xydata, r.hzf_id);

            $("#xsd_kh_id").zcombobox("setMap", { id: r.hzf_id, jc: r.hzf_qc});
/*
            $("#xsd_gc_id").gccombobox(r.hzf_id, {
                onLoadSuccess: function () {
                    if (r.gc_id && $(this).combobox('getData')) {
                        $(this).combobox('setValue', r.gc_id);
                    }
                }
            });*/
        });
    }

    if (r.sbgs_id)
        $("#xsd_sbgs_id").val(r.sbgs_id);
    if (r.sbbm_id)
        $("#xsd_sbbm_id").val(r.sbbm_id);
    if (r.sbr_id)
        $("#xsd_sbr_id").val(r.sbr_id);
    if (r.sbgs_jc)
        $("#xsd_sbgs_jc").val(r.sbgs_jc);
    if (r.sbbm_qc)
        $("#xsd_sbbm_qc").val(r.sbbm_qc);
    if (r.sbr_qc)
        $("#xsd_sbr_qc").val(r.sbr_qc);

    if (r.wlfgs_id) {
        $("#xsd_xsgs_id").combobox('setValue', r.wlfgs_id);
        $("#xsd_xsgs_id").combobox('readonly', true);
       // $("#xsd_thck_id").combobox('reload', $.webPath() + '/organ/ck/ckmcXsdList?ssgsjgId=' + r.wlfgs_id);
    }


    if (r.fhzr_id)
        $("#xsd_fyzr_id").combobox('setValue', r.fhzr_id);
    if (r.jhdd)
        $("#xsd_jhdz").val(r.jhdd);
    if (r.jhsj)
        $("#xsd_jhsj").datebox('setValue', r.jhsj);

    $("#xsd_xslx_mc").val("合同销售");
    $("[name='xsd.xslx']").val('htxs');

}

function initXsdContent() {
    var xslx = $("[name='xsd.xslx']").val();

    if ($("[name='xsd.id']").val()) {
        $("#xsd_xsgs_id").combobox({
            onLoadSuccess: function () {
                $("#xsd_xsgs_id").combobox('readonly', true);
            }
        })

    }

    if (xslx == "kcls") {
        $("#xsd_kh_id").qyjgzcombobox({
            onSuccess: function () {
                $("#xsd_kh_id").zcombobox("setMap", { id: $("#kh_id").val(), jc: $("#kh_jc").val()});
               /* $("#xsd_gc_id").gccombobox($("#kh_id").val());*/
            },
            onSelect: function () {
                var xsd_kh = $("#xsd_kh_id").combobox('getValue');
              /*  $("#xsd_gc_id").gccombobox(xsd_kh);*/
            }
        });
        $("#xsd_addlskh_Tool").css('display', 'block');
        $("#xsd_xslx_mc").val("库存零售");
        $("#xsd_xsht").css('display', 'none');
        $("#xsd_xsht_id").attr("required", false);
        $('#xsd_sl').slsjzdcombobox("sl");
    } else if ($("[name='xsd.xslx']").val() == "htxs") {
        $("#xsd_xslx_mc").val("合同销售");
        $("#lj_xsd").css('display', 'none');
        $("#xsd_lj_id").attr("required", false);
        $("#xsd_lj_id").combobox({valueField: 'id', textField: 'mc'})
        $('#xsd_sl').slsjzdcombobox("sl");
    } else if ($("[name='xsd.xslx']").val() == "bgxs") {
        $('#xsd_sl').slsjzdcombobox("sl");
        $("#xsd_xslx_mc").val("保供销售");
        $("#xsd_xsht").css('display', 'none');
        $("#xsd_xsht_id").attr("required", false);
    }

    if (!$("[name='xsd.lj.id']").val()) {
        if ($("[name='xsd.xslx']").val() == "bgxs" && $("#xsd_lj_id").length > 0) {
            $("#xsd_lj_id").ljcombobox($("#xsd_zggsId").val(), 3, {
                onChange: function (newValue, oldValue) {
                    if (newValue != oldValue) {
                        $.post($.webPath() + '/organ/ljwh/ljinfosxy', {'ljId': newValue}, function (data) {
                            var xydata = [];
                            $(data).each(function (i, item) {
                                if (item.lx == 'xy') {    //下游
                                    xydata.push(item);
                                }
                            })
                            $("#xsd_kh_id").zcombobox("setMap", { id: xydata[0].id, jc: xydata[0].jc});

                          /*  $("#xsd_gc_id").gccombobox(xydata[0].id);*/
                        });
                    }
                },
                onSelect: function (record) {
                    $("#xsd_ll").val(record.ll);
                }
            });
        } else if ($("[name='xsd.xslx']").val() == "kcls" && $("#xsd_lj_id").length > 0) {
            $("#xsd_lj_id").ljkclscombobox($("#xsd_zggsId").val(), {
                onSelect: function (record) {
                    $("#xsd_lj_sl").val(record.sl);
                    $("#xsd_ll").val(record.ll);
                }
            });
        }
    }
}

//合计计算
function countSumXsd() {
    var sumxscb = 0;
    var sumjs = 0;
    var sumsbsl = 0;
    var sumhse = 0;
    var sumbhse = 0;
    var data = $("#xsd_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var xscb = parseFloat(data.rows[i]["xscb"]);
        var js = parseFloat(data.rows[i]["js"]);
        var sbsl = parseFloat(data.rows[i]["sbsl"]);
        var hse = parseFloat(data.rows[i]["hse"]);
        var bhse = parseFloat(data.rows[i]["bhse"]);
        xscb = isNaN(xscb) ? 0 : xscb;
        js = isNaN(js) ? 0 : js;
        sbsl = isNaN(sbsl) ? 0 : sbsl;
        hse = isNaN(hse) ? 0 : hse;
        bhse = isNaN(bhse) ? 0 : bhse;
        sumxscb += xscb;
        sumjs += js;
        sumsbsl += sbsl;
        sumhse += hse;
        sumbhse += bhse;
    }
    addFooter(sumxscb, sumjs, sumsbsl, sumhse, sumbhse);

}

function addFooter(sumxscb, sumjs, sumsbsl, sumhse, sumbhse) {
    var footer = null;
    footer = [
        {"wzgg.code": "合计", "xscb": formatJe(sumxscb), "js": formatSl(sumjs),
            "sbsl": formatSl(sumsbsl), "hse": formatJe2(sumhse), "bhse": formatJe2(sumbhse)}
    ];
    if (footer != null)
        $("#xsd_mx").edatagrid('reloadFooter', footer);
}

function changeEidtToSum(rowIndex, jsEditor, sbslEditor, hseEditor, bhseEditor, hsjEditor, bhsjEditor) {
    //var bhsj = Math.round($(bhsjEditor.target).val() * 10000) / 10000;
    var hsj = Math.round($(hsjEditor.target).val() * 10000) / 10000;
    var sl = Math.round($(sbslEditor.target).val() * 10000) / 10000;
    var bhsj = Math.round($(bhsjEditor.target).numberbox('getValue') * 10000) / 10000;

    $(bhseEditor.target).numberbox('setValue', Math.round(multiply(bhsj, sl) * 100) / 100);
    $(hseEditor.target).numberbox('setValue', Math.round(multiply(hsj, sl) * 100) / 100);
    var js = parseFloat($(jsEditor.target).numberbox('getValue'));
    var hse = parseFloat($(hseEditor.target).numberbox('getValue'));
    var bhse = parseFloat($(bhseEditor.target).numberbox('getValue'));
    js = isNaN(js) ? 0 : js;
    sl = isNaN(sl) ? 0 : sl;
    hse = isNaN(hse) ? 0 : hse;
    bhse = isNaN(bhse) ? 0 : bhse;
    var sumxscb = 0;
    var sumjs = 0;
    var sumsbsl = 0;
    var sumhse = 0;
    var sumbhse = 0;
    var data = $("#xsd_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        if (i == rowIndex) {
            var c_xscb = parseFloat(data.rows[i]['xscb']);
            c_xscb = isNaN(c_xscb) ? 0 : c_xscb;
            sumxscb += parseFloat(c_xscb);
            sumjs += parseFloat(js);
            sumsbsl += parseFloat(sl);
            sumhse += parseFloat(hse);
            sumbhse += parseFloat(bhse);
        } else {
            var t_xscb = parseFloat(data.rows[i]['xscb']);
            var t_js = parseFloat(data.rows[i]['js']);
            var t_sbsl = parseFloat(data.rows[i]['sbsl']);
            var t_hse = parseFloat(data.rows[i]['hse']);
            var t_bhse = parseFloat(data.rows[i]['bhse']);
            t_xscb = isNaN(t_xscb) ? 0 : t_xscb;
            t_js = isNaN(t_js) ? 0 : t_js;
            t_sbsl = isNaN(t_sbsl) ? 0 : t_sbsl;
            t_hse = isNaN(t_hse) ? 0 : t_hse;
            t_bhse = isNaN(t_bhse) ? 0 : t_bhse;
            sumxscb += parseFloat(t_xscb);
            sumjs += parseFloat(t_js);
            sumsbsl += parseFloat(t_sbsl);
            sumhse += parseFloat(t_hse);
            sumbhse += parseFloat(t_bhse);
        }
    }
    addFooter(sumxscb, sumjs, sumsbsl, sumhse, sumbhse);
}

//统计单一属性的方法
function countSumXsdmxforfylbChange(property) {
    var sum = 0;
    var data = $("#xsd_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var pro = parseFloat(data.rows[i][property]);
        pro = isNaN(pro) ? 0 : pro;
        sum += pro;
    }
    return sum;
}

//销售单筛选物资明细弹框页面
function searchXshtCorKhWindow(fn, fw, xshtId) {
    var win = $.window({
        title: "筛选物资明细",
        url: $.webPath() + '/xsgl/xsdgl/search_XshtCorKh?fw=' + (fw == undefined ? "" : fw) + '&xshtId=' + xshtId,
        width: 1024,
        height: 500,
        model: true,
        maximizable: true,
        maximized: true,
        isMax: true,
        buttons: [
            {
                text: '确定',
                handler: function () {
                    var selected = $(win).find("#xsht_kh_checked_grid").datagrid("getData");
                    selected = selected.rows;
                    fn(selected);
                    $(win).dialog('close');
                }
            }
        ]
    });
}

//筛选物资明细反馈回函数
function shaixuanwuzimingxifankuihanshuo(data) {
    var rowdatas = $.map(data, function (val, i) {
        var temp = {
            'kh.id': val['kh.id'],
            'kh.khbm': val['kh.khbm'],
            'wzgg.id': val['wzgg.id'],
            'wzgg.oldcode': val['wzgg.oldcode'],
            'wzgg.code': val['wzgg.code'],
            'wzgg.name': val['wzgg.name'],
            'wzgg.ggxh': val['wzgg.ggxh'],
            'wzgg.cz': val['wzgg.cz'],
            'wzgg.th': val['wzgg.th'],
            'wzgg.dw': val['wzgg.dw'],
            'cd.id': val['cd.id'],
            'cd.z': val['cd.z'],
            'kkdsl': val['kkdsl'],
            'sbsl': val['sbsl'],
            'js': val['js'],
            'ck': '',
            'xscb': val['xscb'],
            'jzfs.id': 22,
            'hsj': val.hsj,
            'bhse': val.bhse,
            'hse': val.hse,
            'bhsj': val.bhsj,
            'xszxh': val['xszxh'],
            'carNo': val['carNo'],
            'bindNo': val['bindNo']
        };
        return temp;
    });
    $('#xsd_mx').datagrid('loadData', { total: 0, rows: [] });//清空数据
    $.each(rowdatas, function (i, obj) {
        $("#xsd_mx").edatagrid('appendRow', obj);
    });
}
